package com.yunma.listen;

import com.common.bean.ParameterIncludeBean;
import com.common.bean.RequestParameterTemplate;
import com.string.widget.util.ValueWidget;
import com.yunma.autotest.RequestPanel;
import com.yunma.util.TableUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 黄威 on 05/11/2016.<br >
 */
public class OptionalParametersListener implements ActionListener {
    private RequestPanel requestPanel;

    public OptionalParametersListener(RequestPanel requestPanel) {
        super();
        this.requestPanel = requestPanel;
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String command = event.getActionCommand();
        if (ValueWidget.isNumeric(command)) {
            int selected = Integer.parseInt(command);
//          RequestParameterTemplate requestParameterTemplate=this.requestPanel.getRequestParameterTemplate(command);
            List<RequestParameterTemplate> requestParameterTemplates = this.requestPanel.getRequestParameterTemplates();
            RequestParameterTemplate requestParameterTemplate = null;
            if (null != requestParameterTemplates) {
                requestParameterTemplate = requestParameterTemplates.get(selected);
            }
            if (null != requestParameterTemplate) {
                Map<String, String> parametersMap = requestParameterTemplate.getParameters();
                List<ParameterIncludeBean> parameters = this.requestPanel.getTableParameters();
                for (Iterator iterator = parametersMap.keySet().iterator(); iterator.hasNext(); ) {
                    String key = (String) iterator.next();
                    String val = parametersMap.get(key);
                    int index = TableUtil.isContains2(parameters, key);
                    if (index == -1) {
                        continue;
                    }
                    parameters.get(index).setValue(val);
                }

                this.requestPanel.updateParameter(this.requestPanel.getRequestInfoBean(true), parameters);
                if (!ValueWidget.isNullOrEmpty(requestParameterTemplate.getServerIp())) {
                    requestPanel.setServerIp(requestParameterTemplate.getServerIp());
                }
                if (requestPanel.isSendRightNow()) {
                    this.requestPanel.cleanUpTA();
                    this.requestPanel.runWithProgress(null);
                } else {
                    int result = JOptionPane.showConfirmDialog(null, "Are you sure to 发送请求 ?", "确认",
                            JOptionPane.OK_CANCEL_OPTION);
                    if (result == JOptionPane.OK_OPTION) {
                        this.requestPanel.cleanUpTA();
                        this.requestPanel.runWithProgress(null);
                    }
                }
            }
        }

    }
}
